package com.ezjie.login;

import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.InputType;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.ezjie.baselib.core.base.BaseFragmentActivity;
import com.ezjie.baselib.util.AppUtil;
import com.ezjie.baselib.util.LogUtils;
import com.ezjie.baselib.util.NetworkUtil;
import com.ezjie.baselib.util.OnDialogBtnClickImpl;
import com.ezjie.login.core.base.BaseBean;
import com.ezjie.login.core.http.HttpRequestAbstractCallBack;
import com.ezjie.login.db.UserInfoDB;
import com.ezjie.login.model.UserData;
import com.ezjie.login.model.UserDetail;
import com.ezjie.login.model.UserInfo;
import com.ezjie.login.task.RegisterTask;
import com.ezjie.login.util.UmengPages;
import com.ezjie.login.widget.AppWarnDialog;
import com.ezjie.login.widget.CustomDialog;
import com.ezjie.login.widget.LinearLayoutView;
import com.ezjie.login.widget.LinearLayoutView.KeyBordStateListener;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.exception.HttpException;
import com.umeng.analytics.MobclickAgent;

/**
 * 填写昵称
 * @author renyangyang
 *
 */
//@ContentView(R.layout.layout_register_name)
public class NickRegActivity extends BaseFragmentActivity {
	
	private ImageView login_back_btn;
	private LinearLayoutView ll_root_view;
	private ImageView login_logo;
	private EditText et_nickName;
	private EditText et_password;
	private ImageView password_isshow;
	private Button register_btn;
	private ImageView register_xieyi_img;//协议图片按钮
	private TextView tv_register_xieyi;//查看用户协议
	
	private boolean isOpen = true;//判断密码是否显示
	private boolean isAgree = true;//同意协议
	private String mobile;
	private String verify_code;
	private RegisterTask registerTask;
	private UserInfoDB mUserInfoDB;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.layout_register_name);
		login_back_btn = (ImageView)super.findViewById(R.id.login_back_btn);
		ll_root_view = (LinearLayoutView)super.findViewById(R.id.ll_root_view);
		login_logo = (ImageView)super.findViewById(R.id.login_logo);
		et_nickName = (EditText)super.findViewById(R.id.et_username);
		et_password = (EditText)super.findViewById(R.id.password);
		password_isshow = (ImageView)super.findViewById(R.id.password_isshow);
		register_btn = (Button)super.findViewById(R.id.register_btn);
		register_xieyi_img = (ImageView)super.findViewById(R.id.register_xieyi_img);
		tv_register_xieyi = (TextView)super.findViewById(R.id.tv_register_xieyi);
		ViewUtils.inject(this);
		registerTask = new RegisterTask(this);
		mUserInfoDB = new UserInfoDB(this);
		init();
	}
	
	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		MobclickAgent.onPageStart(UmengPages.PAGE_NICK_REG);
	}
	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
		MobclickAgent.onPageEnd(UmengPages.PAGE_NICK_REG);
	}
	
	private void init(){
		Intent intent = getIntent();
		mobile = intent.getStringExtra("mobile");
		verify_code = intent.getStringExtra("verify_code");
		
		login_back_btn.setOnClickListener(this);
		password_isshow.setOnClickListener(this);
		register_btn.setOnClickListener(this);
		register_xieyi_img.setOnClickListener(this);
		tv_register_xieyi.setOnClickListener(this);
		et_nickName.addTextChangedListener(new TextWatcher() {
			
			@Override
			public void onTextChanged(CharSequence s, int start, int before, int count) {
			}
			
			@Override
			public void beforeTextChanged(CharSequence s, int start, int count, int after) {
			}
			
			@Override
			public void afterTextChanged(Editable s) {
				regEnable();
			}
		});
		et_password.addTextChangedListener(new TextWatcher() {
			
			@Override
			public void onTextChanged(CharSequence s, int start, int before, int count) {
			}
			
			@Override
			public void beforeTextChanged(CharSequence s, int start, int count, int after) {
			}
			
			@Override
			public void afterTextChanged(Editable s) {
				regEnable();
				
			}
		});
		ll_root_view.setKeyBordStateListener(new KeyBordStateListener() {
			
			@Override
			public void stateChange(int state) {
				switch (state) {
				case LinearLayoutView.KEYBORAD_HIDE:
					login_logo.setVisibility(View.VISIBLE);
					break;
				case LinearLayoutView.KEYBORAD_SHOW:
					login_logo.setVisibility(View.GONE);
					break;
				}
				
			}
		});
	}
	
	/**
	 * 判断登录按钮是否可以点击
	 * @param username
	 * @param password
	 */
	private void regEnable(){
		String nickName = et_nickName.getText().toString();
		String password = et_password.getText().toString();
		if (TextUtils.isEmpty(nickName)||TextUtils.isEmpty(password)||password.length()<6||!isAgree||nickName.length()<6) {
			register_btn.setEnabled(false);
		}else {
			register_btn.setEnabled(true);
		}
	}
	
	@Override
	public void onClickEvent(View view) {
		
		if(view.getId()==R.id.login_back_btn){
			this.finish();
		}else if (view.getId() == R.id.password_isshow){
			//密码是否显示
			if (isOpen) {
				//显示密码
				isOpen = false;
				password_isshow.setImageResource(R.drawable.paw_hidder);
				et_password.setInputType(InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
			}else {//隐藏密码
				isOpen = true;
				password_isshow.setImageResource(R.drawable.paw_show);
				et_password.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
			}
		}else if(view.getId() == R.id.register_btn){
			if (AppUtil.isFastClick()) {
				return;
			}
			doReg();
		}else if(view.getId() == R.id.register_xieyi_img){
			//同意协议按钮
			if (isAgree) {
				isAgree = false;
				register_xieyi_img.setImageResource(R.drawable.register_uncheck);
				regEnable();
			}else {
				isAgree = true;
				register_xieyi_img.setImageResource(R.drawable.register_check);
				regEnable();
			}
		}else if(view.getId() ==R.id.tv_register_xieyi){
			//查看协议
			showXieyiDialog();
		}

	}
	
	private void showXieyiDialog() {
		final CustomDialog dialog = new CustomDialog(NickRegActivity.this,R.layout.register_xieyi, R.style.customDialog);
		dialog.setCanceledOnTouchOutside(true);
		dialog.show();

		LinearLayout btn_yes = (LinearLayout) dialog.findViewById(R.id.dialog_ll);
		TextView xieyi = (TextView) dialog.findViewById(R.id.tv_xieyi);
		btn_yes.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				if (dialog != null
						&& dialog.isShowing()) {
					dialog.cancel();
				}
			}
		});
		xieyi.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				if (dialog != null
						&& dialog.isShowing()) {
					dialog.cancel();
				}
			}
		});
	}
	
	private void doReg(){
		if (!NetworkUtil.isNetworkAvailable(this)) {
			AppUtil.showToast(this, R.string.no_network);
			return;
		}
		String nickName = et_nickName.getText().toString();
		String password = et_password.getText().toString();
		if (TextUtils.isEmpty(nickName)) {
			AppUtil.showToast(this, R.string.reg_nick_not_null);
			return;
		}
		if (TextUtils.isEmpty(password)) {
			AppUtil.showToast(this, R.string.reg_password_not_null);
			return;
		}
		if (!AppUtil.validateUserName(nickName)) {
			AppUtil.showToast(this, R.string.reg_input_correct_nickname);
			return;
		}
		if (!AppUtil.passwordFormat(password)) {
			AppUtil.showToast(this, R.string.login_input_correct_password);
			return;
		}
		registerTask.doReg(mobile, password, verify_code, nickName, new HttpRequestAbstractCallBack(this,false) {
			@Override
			public void onStartCallBack() {
				// TODO Auto-generated method stub
				super.onStartCallBack();
				AppUtil.showProgressDialog(NickRegActivity.this);
			}
			@Override
			public void onSuccessCallBack(String result) {
				// TODO Auto-generated method stub
				super.onSuccessCallBack(result);
				AppUtil.dismissProgressDialog();
				LogUtils.d(result);
				try {
					BaseBean baseBean = JSON.parseObject(result, BaseBean.class);
					if (baseBean != null) {
						if (baseBean.getStatus_code()==200) {
							//注册成功 跳转到回到之前界面
							AppUtil.showToast(NickRegActivity.this, R.string.reg_success);
							
							UserInfo info = JSON.parseObject(result, UserInfo.class);
							if (info != null && info.getStatus_code() == 200) {
								UserData data = info.getData();
								if (data != null) {
									String login_token = data.getLogin_token();
									UserDetail user = data.getUser();
									user.login_key = login_token;
									user.islogin = 1;
									//判断uid是否存在
									boolean existUid = mUserInfoDB.isExistUid(user.uid);
									if (existUid) {
										mUserInfoDB.update(user);
									}else {
										mUserInfoDB.insert(user);
									}
									NickRegActivity.this.setResult(RESULT_OK);
									NickRegActivity.this.finish();
								}
								
							}
							
							
						}else {
							String msg = baseBean.getMsg();
							if (TextUtils.isEmpty(msg)) {
								msg = NickRegActivity.this.getResources().getString(R.string.reg_fail);
							}
							final AppWarnDialog appWarnDialog = new AppWarnDialog(NickRegActivity.this, R.style.customDialog);
							appWarnDialog.show();
							appWarnDialog.setOneButton(true);
							appWarnDialog.setMessage(msg);
							appWarnDialog.setKnowButton(R.string.confirm);
							appWarnDialog.setListener(new OnDialogBtnClickImpl() {
								public void onKnowClick() {
									appWarnDialog.dismiss();
								}
							});
						}
					}
				} catch (Exception e) {
					LogUtils.exception(e);
				}
			}
			@Override
			public void onFailureCallBack(HttpException error, String msg) {
				// TODO Auto-generated method stub
				super.onFailureCallBack(error, msg);
				AppUtil.dismissProgressDialog();
        		AppUtil.showToast(NickRegActivity.this, R.string.load_net_data_failure);
			}
		});
	}

}
